package dustdispatcher;


/**
 * This class is intented to be extended by any one that want to add
 * functionality to Dust. This class has the peculiarity that makes use of the
 * Dispatcher module in order to not exhaust system resources.
 * 
 * If you want to create fair tasks that shares the system with each other
 * tasks and doesn't exhaust the system use this class. DustTask are not
 * dispatchable, instead they are executed directly. Read DustTask
 * documentation for more information.
 * 
 * @author ole
 */
public class DispatchableTask extends DustTask {	
	/**
	 * Class constructor. A DispatchableTask is a DustTask that make use of
	 * the Dispatcher module. When it finish it tells the Dispatcher that
	 * it can run another task.
	 */
	public DispatchableTask() {
		super();
	}
	
	/**
	 * TODO: To make all the dispatching subsystem works the tasks extending
	 * DispatchableTask needs to call EXPLICITLY this method finalize()
	 * because this method interacts with DustDispatcher in order to tell it
	 * that this task has finished its job and trigger DustDispatcher logic,
	 * remove this task from the running tasks queue and wake up another task
	 * if the limit of tasks running at a time is not reached. This is of
	 * course ugly and painfully, plus if the programmer forgot to call
	 * finalize() the DustDispatcher will never run the tasks that are waiting.
	 * 
	 * The nicest way to solve this (imho) is make the DispatchableTasks
	 * execute a function (call it callback) for when the run() method finish.
	 * The point here is study if there is a way to detect the return of the
	 * run() method.
	 */
	
	/**
	 * When a DispatchableTask will be destroyed we need to tell the
	 * DustDispatcher to remove it from the running queue.
	 */
	@Override
	public final void finalize() {
		try {
			super.finalize();
		}
		catch (Throwable e) {
			e.printStackTrace();
		}
		
		DustDispatcher.removeTask(this);
	}
}
